#!/bin/bash

# Nginx HTTPS 反向代理配置脚本
# 包含Nginx自动安装功能
# 使用现有SSL证书：/etc/ssl/域名/ 目录下的证书文件

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_input() {
    echo -e "${BLUE}[INPUT]${NC} $1"
}

log_success() {
    echo -e "${PURPLE}[SUCCESS]${NC} $1"
}

# 检查是否以root权限运行
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要以root权限运行"
        exit 1
    fi
}

# 检测系统类型
detect_os() {
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$NAME
        OS_VERSION=$VERSION_ID
    elif type lsb_release >/dev/null 2>&1; then
        OS=$(lsb_release -si)
        OS_VERSION=$(lsb_release -sr)
    elif [[ -f /etc/redhat-release ]]; then
        OS=$(cat /etc/redhat-release | awk '{print $1}')
        OS_VERSION=$(cat /etc/redhat-release | awk '{print $3}')
    else
        OS=$(uname -s)
        OS_VERSION=$(uname -r)
    fi
    
    log_info "检测到操作系统: $OS $OS_VERSION"
    echo $OS
}

# 安装Nginx
install_nginx() {
    local os_type=$1
    
    log_info "开始安装 Nginx..."
    
    case $os_type in
        *Ubuntu*|*Debian*)
            log_info "使用APT安装Nginx..."
            
            # 更新软件包列表
            apt-get update
            
            # 安装必要依赖
            apt-get install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring
            
            # 导入Nginx官方签名密钥
            curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
                | tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
            
            # 添加Nginx官方源
            echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
            http://nginx.org/packages/mainline/$(lsb_release -is | tr '[:upper:]' '[:lower:]') $(lsb_release -cs) nginx" \
                | tee /etc/apt/sources.list.d/nginx.list
            
            # 设置优先级
            echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
                | tee /etc/apt/preferences.d/99nginx
            
            # 更新并安装Nginx
            apt-get update
            apt-get install -y nginx
            
            ;;
        
        *CentOS*|*Red*Hat*|*Fedora*|*Amazon*)
            log_info "使用YUM安装Nginx..."
            
            # 创建Nginx仓库文件
            cat > /etc/yum.repos.d/nginx.repo << EOF
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF
            
            # 安装EPEL仓库（CentOS/RHEL）
            if [[ $os_type == *"CentOS"* ]] || [[ $os_type == *"Red Hat"* ]]; then
                yum install -y epel-release
            fi
            
            # 安装Nginx
            yum install -y nginx
            
            ;;
        
        *)
            log_error "不支持的操作系统: $os_type"
            log_info "请手动安装Nginx后重新运行此脚本"
            exit 1
            ;;
    esac
    
    # 启动并启用Nginx服务
    systemctl enable nginx
    systemctl start nginx
    
    # 验证安装
    if systemctl is-active --quiet nginx; then
        nginx_version=$(nginx -v 2>&1 | cut -d'/' -f2)
        log_success "Nginx 安装成功 - 版本: $nginx_version"
    else
        log_error "Nginx 服务启动失败"
        systemctl status nginx --no-pager
        exit 1
    fi
}

# 配置Nginx基础设置
configure_nginx_basic() {
    log_info "配置Nginx基础设置..."
    
    # 备份原始配置文件
    if [[ ! -f /etc/nginx/nginx.conf.backup ]]; then
        cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
        log_info "已备份原始nginx.conf文件"
    fi
    
    # 创建必要的目录
    mkdir -p /etc/nginx/sites-available
    mkdir -p /etc/nginx/sites-enabled
    
    # 确保nginx.conf包含sites-enabled目录
    if ! grep -q "sites-enabled" /etc/nginx/nginx.conf; then
        # 在http块内添加include
        sed -i '/http {/a\    include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf
    fi
    
    # 移除默认配置（如果存在）
    if [[ -f /etc/nginx/sites-enabled/default ]]; then
        rm -f /etc/nginx/sites-enabled/default
    fi
    
    log_success "Nginx基础配置完成"
}

# 检查端口是否被占用
check_port_available() {
    local port=$1
    # 使用 ss 命令替代 netstat（更现代的工具）
    if command -v ss &> /dev/null; then
        if ss -tuln | grep -q ":${port} "; then
            return 1  # 端口被占用
        else
            return 0  # 端口可用
        fi
    elif command -v netstat &> /dev/null; then
        if netstat -tuln | grep -q ":${port} "; then
            return 1  # 端口被占用
        else
            return 0  # 端口可用
        fi
    else
        log_warn "无法检查端口状态，请手动确认端口 ${port} 是否可用"
        return 0  # 假设端口可用
    fi
}

# 检查证书文件是否存在
check_certificates() {
    local domain=$1
    local cert_dir="/etc/ssl/${domain}"
    local fullchain_file="${cert_dir}/fullchain.pem"
    local privkey_file="${cert_dir}/privkey.pem"
    
    if [[ ! -d "$cert_dir" ]]; then
        log_error "证书目录不存在: $cert_dir"
        log_info "请确保证书文件位于: /etc/ssl/${domain}/"
        log_info "或者使用以下命令创建证书目录:"
        echo "  mkdir -p /etc/ssl/${domain}"
        echo "  # 将fullchain.pem和privkey.pem放入上述目录"
        exit 1
    fi
    
    if [[ ! -f "$fullchain_file" ]]; then
        log_error "完整证书链文件不存在: $fullchain_file"
        exit 1
    fi
    
    if [[ ! -f "$privkey_file" ]]; then
        log_error "私钥文件不存在: $privkey_file"
        exit 1
    fi
    
    log_info "SSL证书检查通过:"
    echo "   证书目录: $cert_dir"
    echo "   完整证书: $fullchain_file"
    echo "   私钥文件: $privkey_file"
    echo ""
    
    # 显示证书文件列表
    log_info "证书文件列表:"
    ls -la "$cert_dir"/
    
    # 验证证书有效期（可选）
    if command -v openssl &> /dev/null; then
        log_info "证书信息:"
        openssl x509 -in "$fullchain_file" -noout -subject -dates 2>/dev/null || log_warn "无法读取证书信息"
    fi
}

# 检查Nginx是否已安装
check_nginx_installed() {
    if ! command -v nginx &> /dev/null; then
        log_warn "Nginx 未安装"
        
        # 询问是否安装
        log_input "是否自动安装Nginx? (Y/n):"
        read -r INSTALL_NGINX
        INSTALL_NGINX=${INSTALL_NGINX:-Y}
        
        if [[ $INSTALL_NGINX =~ ^[Yy]$ ]]; then
            local os_type=$(detect_os)
            install_nginx "$os_type"
            configure_nginx_basic
        else
            log_info "请手动安装Nginx后重新运行此脚本"
            log_info "安装命令参考:"
            echo "  Ubuntu/Debian: apt-get install nginx -y"
            echo "  CentOS/RHEL: yum install nginx -y"
            exit 1
        fi
    else
        log_info "Nginx 已安装"
        nginx_version=$(nginx -v 2>&1 | cut -d'/' -f2)
        log_info "Nginx 版本: $nginx_version"
    fi
}

# 获取用户输入
get_user_input() {
    log_input "请输入要配置的域名 (例如: example.com):"
    read -r DOMAIN
    
    # 验证域名格式
    if [[ ! $DOMAIN =~ ^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
        log_error "域名格式不正确"
        exit 1
    fi
    
    log_input "请输入代理目标服务器IP (默认: 127.0.0.1):"
    read -r SERVER_IP
    SERVER_IP=${SERVER_IP:-127.0.0.1}
    
    log_input "请输入代理目标端口 (例如: 8080, 3000, 5000 等):"
    read -r SERVER_PORT
    
    # 验证端口号
    if [[ ! $SERVER_PORT =~ ^[0-9]+$ ]] || [ $SERVER_PORT -lt 1 ] || [ $SERVER_PORT -gt 65535 ]; then
        log_error "端口号必须是 1-65535 之间的数字"
        exit 1
    fi
    
    # 询问是否监听HTTP
    ENABLE_HTTP=false
    HTTP_PORT=""
    log_input "是否启用HTTP监听? (y/N):"
    read -r ENABLE_HTTP_CONFIRM
    if [[ $ENABLE_HTTP_CONFIRM =~ ^[Yy]$ ]]; then
        ENABLE_HTTP=true
        log_input "请输入HTTP监听端口 (默认: 8080):"
        read -r HTTP_PORT
        HTTP_PORT=${HTTP_PORT:-8080}
        
        # 验证HTTP端口
        if [[ ! $HTTP_PORT =~ ^[0-9]+$ ]] || [ $HTTP_PORT -lt 1 ] || [ $HTTP_PORT -gt 65535 ]; then
            log_error "HTTP端口号必须是 1-65535 之间的数字"
            exit 1
        fi
        
        # 检查HTTP端口是否被占用
        if ! check_port_available $HTTP_PORT; then
            log_warn "HTTP端口 $HTTP_PORT 已被占用，请选择其他端口"
            exit 1
        fi
    fi
    
    # 询问是否监听HTTPS
    ENABLE_HTTPS=false
    HTTPS_PORT=""
    log_input "是否启用HTTPS监听? (y/N):"
    read -r ENABLE_HTTPS_CONFIRM
    if [[ $ENABLE_HTTPS_CONFIRM =~ ^[Yy]$ ]]; then
        ENABLE_HTTPS=true
        
        # 检查证书是否存在
        check_certificates "$DOMAIN"
        
        log_input "请输入HTTPS监听端口 (默认: 8443):"
        read -r HTTPS_PORT
        HTTPS_PORT=${HTTPS_PORT:-8443}
        
        # 验证HTTPS端口
        if [[ ! $HTTPS_PORT =~ ^[0-9]+$ ]] || [ $HTTPS_PORT -lt 1 ] || [ $HTTPS_PORT -gt 65535 ]; then
            log_error "HTTPS端口号必须是 1-65535 之间的数字"
            exit 1
        fi
        
        # 检查HTTPS端口是否被占用
        if ! check_port_available $HTTPS_PORT; then
            log_warn "HTTPS端口 $HTTPS_PORT 已被占用，请选择其他端口"
            exit 1
        fi
    fi
    
    # 检查是否至少启用了一个监听
    if [[ "$ENABLE_HTTP" == false && "$ENABLE_HTTPS" == false ]]; then
        log_error "必须至少启用HTTP或HTTPS中的一个监听"
        exit 1
    fi
    
    # 检查端口是否相同
    if [[ "$ENABLE_HTTP" == true && "$ENABLE_HTTPS" == true && "$HTTP_PORT" == "$HTTPS_PORT" ]]; then
        log_error "HTTP端口和HTTPS端口不能相同"
        exit 1
    fi
    
    # 构建代理目标地址
    PROXY_PASS="http://${SERVER_IP}:${SERVER_PORT}"
    
    # 显示配置摘要
    log_info "配置摘要:"
    echo "   域名: $DOMAIN"
    echo "   代理目标: $PROXY_PASS"
    if [[ "$ENABLE_HTTP" == true ]]; then
        echo "   HTTP监听端口: $HTTP_PORT"
    else
        echo "   HTTP监听: 禁用"
    fi
    if [[ "$ENABLE_HTTPS" == true ]]; then
        echo "   HTTPS监听端口: $HTTPS_PORT"
        echo "   证书目录: /etc/ssl/${DOMAIN}/"
    else
        echo "   HTTPS监听: 禁用"
    fi
    echo ""
    
    log_input "确认以上配置? (y/N):"
    read -r CONFIRM
    if [[ ! $CONFIRM =~ ^[Yy]$ ]]; then
        log_info "配置已取消"
        exit 0
    fi
}

# 配置Nginx反向代理
configure_nginx() {
    local domain=$1
    local proxy_pass=$2
    local enable_http=$3
    local http_port=$4
    local enable_https=$5
    local https_port=$6
    local cert_dir="/etc/ssl/${domain}"
    local fullchain_file="${cert_dir}/fullchain.pem"
    local privkey_file="${cert_dir}/privkey.pem"
    
    log_info "配置Nginx反向代理..."
    
    # 创建Nginx配置文件
    CONFIG_CONTENT=""
    
    # HTTP 服务器配置（如果启用）
    if [[ "$enable_http" == true ]]; then
        CONFIG_CONTENT+="# HTTP 服务器配置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="server {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    listen ${http_port};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    listen [::]:${http_port};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    server_name ${domain} www.${domain};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        
        # 如果同时启用了HTTPS，则HTTP重定向到HTTPS
        if [[ "$enable_https" == true ]]; then
            CONFIG_CONTENT+="    # 重定向所有HTTP请求到HTTPS"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="    return 301 https://\$server_name:${https_port}\$request_uri;"
            CONFIG_CONTENT+=$'\n'
        else
            # 只启用HTTP时的配置
            CONFIG_CONTENT+="    # 反向代理设置"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="    location / {"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_pass ${proxy_pass};"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_http_version 1.1;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header Host \$host;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header X-Real-IP \$remote_addr;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header X-Forwarded-Proto \$scheme;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        # WebSocket 支持"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header Upgrade \$http_upgrade;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_set_header Connection \"upgrade\";"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        # 超时设置"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_connect_timeout 60s;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_send_timeout 60s;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_read_timeout 60s;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        # 缓冲区设置"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_buffering on;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_buffer_size 4k;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="        proxy_buffers 8 4k;"
            CONFIG_CONTENT+=$'\n'
            CONFIG_CONTENT+="    }"
            CONFIG_CONTENT+=$'\n'
        fi
        CONFIG_CONTENT+="}"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
    fi
    
    # HTTPS 服务器配置（如果启用）
    if [[ "$enable_https" == true ]]; then
        CONFIG_CONTENT+="# HTTPS 服务器配置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="server {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    listen ${https_port} ssl http2;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    listen [::]:${https_port} ssl http2;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    server_name ${domain} www.${domain};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # SSL 证书配置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_certificate ${fullchain_file};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_certificate_key ${privkey_file};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # SSL 安全配置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_protocols TLSv1.2 TLSv1.3;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_prefer_server_ciphers off;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_session_cache shared:SSL:10m;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    ssl_session_timeout 10m;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # 安全头"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    add_header Strict-Transport-Security \"max-age=63072000; includeSubDomains; preload\" always;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    add_header X-Frame-Options DENY always;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    add_header X-Content-Type-Options nosniff always;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    add_header X-XSS-Protection \"1; mode=block\" always;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    add_header Referrer-Policy \"strict-origin-when-cross-origin\" always;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # 反向代理设置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    location / {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_pass ${proxy_pass};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_http_version 1.1;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header Host \$host;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Real-IP \$remote_addr;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Forwarded-Proto \$scheme;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        # WebSocket 支持"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header Upgrade \$http_upgrade;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header Connection \"upgrade\";"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        # 超时设置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_connect_timeout 60s;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_send_timeout 60s;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_read_timeout 60s;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        # 缓冲区设置"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_buffering on;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_buffer_size 4k;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_buffers 8 4k;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    }"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # 静态文件缓存"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_pass ${proxy_pass};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header Host \$host;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Real-IP \$remote_addr;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header X-Forwarded-Proto \$scheme;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        expires 1y;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        add_header Cache-Control \"public, immutable\";"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        add_header Vary \"Accept-Encoding\";"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    }"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # 健康检查端点"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    location /health {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_pass ${proxy_pass};"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        proxy_set_header Host \$host;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        access_log off;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    }"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    # 错误页面"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    error_page 500 502 503 504 /50x.html;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    location = /50x.html {"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="        root /usr/share/nginx/html;"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="    }"
        CONFIG_CONTENT+=$'\n'
        CONFIG_CONTENT+="}"
        CONFIG_CONTENT+=$'\n'
    fi
    
    # 写入配置文件
    echo "$CONFIG_CONTENT" > /etc/nginx/sites-available/${domain}

    # 启用站点配置
    if [ ! -f "/etc/nginx/sites-enabled/${domain}" ]; then
        ln -sf "/etc/nginx/sites-available/${domain}" "/etc/nginx/sites-enabled/"
        log_info "已启用站点配置"
    fi
    
    # 测试Nginx配置
    if nginx -t; then
        log_success "Nginx配置测试通过"
    else
        log_error "Nginx配置测试失败"
        log_info "尝试查看详细错误信息:"
        nginx -t 2>&1
        exit 1
    fi
}

# 配置防火墙
configure_firewall() {
    local enable_http=$1
    local http_port=$2
    local enable_https=$3
    local https_port=$4
    
    log_info "配置防火墙..."
    
    if command -v ufw &> /dev/null && ufw status | grep -q "active"; then
        if [[ "$enable_http" == true ]]; then
            ufw allow ${http_port}
        fi
        if [[ "$enable_https" == true ]]; then
            ufw allow ${https_port}
        fi
        
        local ports=""
        if [[ "$enable_http" == true ]]; then
            ports="${http_port}"
        fi
        if [[ "$enable_https" == true ]]; then
            if [[ -n "$ports" ]]; then
                ports="${ports}, ${https_port}"
            else
                ports="${https_port}"
            fi
        fi
        log_success "UFW防火墙已配置 (开放端口: ${ports})"
        
    elif command -v firewall-cmd &> /dev/null && systemctl is-active --quiet firewalld; then
        if [[ "$enable_http" == true ]]; then
            firewall-cmd --permanent --add-port=${http_port}/tcp
        fi
        if [[ "$enable_https" == true ]]; then
            firewall-cmd --permanent --add-port=${https_port}/tcp
        fi
        firewall-cmd --reload
        
        local ports=""
        if [[ "$enable_http" == true ]]; then
            ports="${http_port}"
        fi
        if [[ "$enable_https" == true ]]; then
            if [[ -n "$ports" ]]; then
                ports="${ports}, ${https_port}"
            else
                ports="${https_port}"
            fi
        fi
        log_success "FirewallD已配置 (开放端口: ${ports})"
    else
        local ports=""
        if [[ "$enable_http" == true ]]; then
            ports="${http_port}"
        fi
        if [[ "$enable_https" == true ]]; then
            if [[ -n "$ports" ]]; then
                ports="${ports}, ${https_port}"
            else
                ports="${https_port}"
            fi
        fi
        log_warn "未找到活动的防火墙工具，请手动开放端口: ${ports}"
    fi
}

# 重启Nginx服务
restart_nginx() {
    log_info "重启Nginx服务..."
    systemctl restart nginx
    
    # 检查Nginx状态
    if systemctl is-active --quiet nginx; then
        log_success "Nginx服务运行正常"
    else
        log_error "Nginx服务启动失败"
        systemctl status nginx --no-pager
        exit 1
    fi
}

# 显示配置信息
show_config_info() {
    local domain=$1
    local proxy_pass=$2
    local enable_http=$3
    local http_port=$4
    local enable_https=$5
    local https_port=$6
    
    log_success "=== 反向代理配置完成 ==="
    echo ""
    echo "📋 配置摘要:"
    echo "   域名: ${domain}"
    echo "   代理目标: ${proxy_pass}"
    if [[ "$enable_http" == true ]]; then
        echo "   HTTP监听端口: ${http_port}"
    else
        echo "   HTTP监听: 禁用"
    fi
    if [[ "$enable_https" == true ]]; then
        echo "   HTTPS监听端口: ${https_port}"
        echo "   证书目录: /etc/ssl/${domain}/"
    else
        echo "   HTTPS监听: 禁用"
    fi
    echo ""
    echo "🔧 管理命令:"
    echo "   Nginx状态: systemctl status nginx"
    echo "   重载配置: systemctl reload nginx"
    echo "   重启服务: systemctl restart nginx"
    echo "   测试配置: nginx -t"
    echo ""
    echo "📁 配置文件:"
    echo "   /etc/nginx/sites-available/${domain}"
    echo "   /etc/nginx/sites-enabled/${domain}"
    echo ""
    echo "🌐 访问地址:"
    if [[ "$enable_http" == true ]]; then
        echo "   HTTP: http://${domain}:${http_port}"
    fi
    if [[ "$enable_https" == true ]]; then
        echo "   HTTPS: https://${domain}:${https_port}"
    fi
    echo ""
    echo "⚠️  请确保:"
    echo "   1. 域名 ${domain} 已正确解析到服务器IP"
    echo "   2. 目标服务 ${proxy_pass} 正在运行"
    if [[ "$enable_http" == true || "$enable_https" == true ]]; then
        local ports=""
        if [[ "$enable_http" == true ]]; then
            ports="${http_port}"
        fi
        if [[ "$enable_https" == true ]]; then
            if [[ -n "$ports" ]]; then
                ports="${ports}, ${https_port}"
            else
                ports="${https_port}"
            fi
        fi
        echo "   3. 防火墙已开放端口: ${ports}"
    fi
    echo ""
}

# 检查现有配置
check_existing_config() {
    local domain=$1
    
    if [ -f "/etc/nginx/sites-available/${domain}" ]; then
        log_warn "发现已存在的配置文件: /etc/nginx/sites-available/${domain}"
        log_input "是否覆盖现有配置? (y/N):"
        read -r OVERWRITE
        if [[ ! $OVERWRITE =~ ^[Yy]$ ]]; then
            log_info "配置已取消"
            exit 0
        fi
    fi
}

# 备份现有配置
backup_existing_config() {
    local domain=$1
    
    if [ -f "/etc/nginx/sites-available/${domain}" ]; then
        local backup_file="/etc/nginx/sites-available/${domain}.backup.$(date +%Y%m%d_%H%M%S)"
        cp "/etc/nginx/sites-available/${domain}" "$backup_file"
        log_info "已备份现有配置: $backup_file"
    fi
}

# 主配置函数
setup_proxy() {
    log_info "开始配置Nginx反向代理..."
    
    check_root
    check_nginx_installed  # 现在包含安装功能
    get_user_input
    check_existing_config "$DOMAIN"
    backup_existing_config "$DOMAIN"
    
    configure_nginx "${DOMAIN}" "${PROXY_PASS}" "${ENABLE_HTTP}" "${HTTP_PORT}" "${ENABLE_HTTPS}" "${HTTPS_PORT}"
    configure_firewall "${ENABLE_HTTP}" "${HTTP_PORT}" "${ENABLE_HTTPS}" "${HTTPS_PORT}"
    restart_nginx
    show_config_info "${DOMAIN}" "${PROXY_PASS}" "${ENABLE_HTTP}" "${HTTP_PORT}" "${ENABLE_HTTPS}" "${HTTPS_PORT}"
}

# 显示使用说明
show_usage() {
    echo "Nginx 反向代理配置脚本 (包含自动安装)"
    echo ""
    echo "使用方法: $0"
    echo ""
    echo "功能:"
    echo "  ✓ 自动检测并安装Nginx"
    echo "  ✓ 配置Nginx反向代理"
    echo "  ✓ 可选择启用HTTP和/或HTTPS"
    echo "  ✓ 支持自定义监听端口"
    echo "  ✓ HTTPS使用现有SSL证书"
    echo ""
    echo "支持的系统:"
    echo "  - Ubuntu/Debian"
    echo "  - CentOS/RHEL/Fedora"
    echo "  - Amazon Linux"
    echo ""
}

# 显示欢迎信息
show_welcome() {
    echo -e "${PURPLE}"
    echo "╔══════════════════════════════════════════════╗"
    echo "║           Nginx 反向代理配置脚本            ║"
    echo "║       自动安装 + HTTP/HTTPS支持             ║"
    echo "╚══════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# 脚本入口
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    show_usage
    exit 0
fi

show_welcome
setup_proxy